package utility

import (
	"io/ioutil"
	"net/http"
	"os"
)

// 获取数据
func FetchData(url string, params string) ([]byte, RespMessage) {
	dataSourceURL := os.Getenv("DATA_SOURCE_URL")
	if dataSourceURL == "" {
		dataSourceURL = "http://127.0.0.1:18080"
	}
	req, err := http.NewRequest("GET", dataSourceURL+"/api/public/"+url+"?"+params, nil)
	if err != nil {
		return []byte{}, RespMessage{Code: 500, Message: "无法创建请求：" + err.Error()}
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return []byte{}, RespMessage{Code: 500, Message: "无法连接到股票数据源：" + err.Error()}
	}
	if resp.StatusCode != http.StatusOK {
		return []byte{}, RespMessage{Code: resp.StatusCode, Message: "无法获取数据，状态码：" + resp.Status}
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, RespMessage{Code: 500, Message: "无法读取股票数据：" + err.Error()}
	}
	return data, RespMessage{Code: 200, Message: "success"}
}
